package cn.itcast.batch.task;

import cn.itcast.batch.utils.MongoUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import java.util.ArrayList;

/**
 * 自定义告警规则新增告警与历史告警统计
 */
public class AlarmNewHistoryMongoTask {
    public static void main(String[] args) {
        /**
         * 1.获得MongoDB客户端连接对象
         * 2.获得被操作的数据库：itcast
         * 3.获得表对象：custom_rule_alarm
         * 4.mongodb查询语句
         * 5.打印
         */
        MongoClient mongoClient = MongoUtil.getConnect();

        MongoDatabase database = mongoClient.getDatabase("itcast");

        MongoCollection<Document> collection = database.getCollection("custom_rule_alarm");

        ArrayList<Document> aggregateList = new ArrayList<>();
        Document doc = new Document();
        doc.append("$project", BasicDBObject.parse("{ \"countNum\":1,\"dataLabel\":{$cond: {if: { $eq: [ \"$state\", 1 ] },then:\"告警数据\",else:\"非告警数据\"}}}"));
        aggregateList.add(doc);
        doc = new Document();
        doc.append("$group",BasicDBObject.parse("{\"_id\":{\"dataLabel\":\"$dataLabel\"},\"countNum\":{ $sum:1}}"));
        aggregateList.add(doc);
        doc = new Document();
        doc.append("$sort",BasicDBObject.parse("{ \"countNum\" : -1}"));
        aggregateList.add(doc);
        MongoCursor<Document> mongoCursor = collection.aggregate(aggregateList).iterator();

        while (mongoCursor.hasNext()){
            System.out.println(mongoCursor.next());
        }

    }
}
